package com.yupi.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: hxu
 * @Date: 2024/05/29/16:38
 * @Description:
 */
@RestController
@Slf4j
@RequestMapping("/queue")
public class QueueController {
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @RequestMapping("/add")
    public void add(String name) {
        CompletableFuture.runAsync(() -> {
            System.out.println("线程执行中:" + name + ".执行人" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, threadPoolExecutor);
    }

    @RequestMapping("/get")
    public String get() {
        Map<String, Object> map = new HashMap<>();
        int size = threadPoolExecutor.getQueue().size();
        map.put("队列长度：", size);
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("任务数量：", taskCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成任务数：" , completedTaskCount);
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("工作中的线程数：", activeCount);
        String result = JSONUtil.toJsonStr(map);
        return result;
    }
}
